import {ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {PageHeaderType} from '../../../../share/components/page-header/page-header.component';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {OptionsInterface} from '../../../../core/services/types';
import {MapPipe, MapSet} from '../../../../share/pipes/map.pipe';
import {ExamsManageService} from '../../../../core/services/http/exams-manage/exams-manage.service';

@Component({
  selector: 'app-add-edit-exams',
  templateUrl: './add-edit-exams.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AddEditExamsComponent implements OnInit {
  validateForm!: FormGroup;
  @Output() returnBack: EventEmitter<any>;
  @Input() currentPageNum!: number;
  @Input() id!: number;
  difficultyOptions: OptionsInterface[] = [];
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '编辑页面',
    breadcrumb: ['考试管理', '考试编辑']
  };
  isDisplay!: boolean;
  listExamOption: OptionsInterface[] = [];
  radioNum: number[] = [];
  judgeNum: number[] = [];
  multiNum: number[] = [];


  constructor(private fb: FormBuilder, private dataService: ExamsManageService, private cdr: ChangeDetectorRef) {
    this.returnBack = new EventEmitter<any>();
    this.isDisplay = false;
  }

  // tslint:disable-next-line:typedef
  get items() {
    return this.validateForm.controls['questionTestBankVos'] as FormArray;
  }

  createRow(): FormGroup {
    return this.fb.group({
      judgeNum: [0, [Validators.required]],
      multiNum: [0, [Validators.required]],
      radioNum: [0, [Validators.required]],
      questionBankId: [null, [Validators.required]]
    });
  }

  async submit(): Promise<any> {
    Object.keys(this.validateForm.controls).forEach(key => {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    });
    if ((this.validateForm.invalid) || this.items.invalid) {
      return;
    }
    const params = this.validateForm.getRawValue();
    if (params.createTime != null) {
      params.startTime = new Date(params.createTime[0]).getTime();
      params.endTime = new Date(params.createTime[1]).getTime();
    }
    let submitHandel = null;
    if (!this.id) {
      submitHandel = this.dataService.addExamsManage(params).toPromise();
    } else {
      params.id = this.id;
      submitHandel = this.dataService.editExamsManage(params).toPromise();
    }
    await submitHandel;
    this.returnBack.emit({refesh: false, pageNo: this.currentPageNum});
  }


  sumScore(): void {
    let totalRaidoNum = 0;
    let totaljudgeNum = 0;
    let totalmultiNum = 0;
    this.radioNum.forEach(item => {
      totalRaidoNum += item * (this.validateForm.get('radioScore')!.value);
    });
    this.multiNum.forEach(item => {
      totalmultiNum += item * (this.validateForm.get('multiScore')!.value);
    });
    this.judgeNum.forEach(item => {
      totaljudgeNum += item * (this.validateForm.get('judgeScore')!.value);
    });
    this.validateForm.get('countScore')!.setValue((totalmultiNum + totaljudgeNum + totalRaidoNum));
  }


  sumNumber(eve: number, i: number, par: string): void {
    switch (par) {
      case 'radioNum':
        this.radioNum[i] = eve;
        break;
      case 'multiNum':
        this.multiNum[i] = eve;
        break;
      case 'judgeNum':
        this.judgeNum[i] = eve;
        break;
      default:
        return;
    }
    this.sumScore();
  }

  returnToList(): void {
    this.returnBack.emit({refesh: false, pageNo: this.currentPageNum});
  }

  add(): void {
    this.items.push(this.createRow());
    this.radioNum.push();
    this.judgeNum.push();
    this.multiNum.push();
  }

  del(index: number): void {
    this.items.removeAt(index);
    this.radioNum.pop();
    this.judgeNum.pop();
    this.multiNum.pop();
    this.sumScore();
  }

  show(e: boolean): void {
    this.isDisplay = e;
  }

  getDetail(): void {
    this.dataService.getExamsManageDetail(this.id).subscribe(newData => {
      this.validateForm.controls['createTime'].setValue([new Date(newData.startTime), new Date(newData.endTime)]);
      newData.questionTestBankVos.forEach((items, index) => {
        this.radioNum.push(items.radioNum);
        this.multiNum.push(items.multiNum);
        this.judgeNum.push(items.judgeNum);
        const field = this.createRow();
        field.patchValue(items);
        this.items.push(field);
      });
      this.validateForm.patchValue(newData);
      this.sumScore();
      this.cdr.markForCheck();
    });
  }

  /*题库下拉请求数据*/
  selectList(): Promise<any> {
    return new Promise(resolve => {
      this.dataService.getExamsManageSelectList({pageSize: 0, pageNum: 0}).subscribe(data => {
        data.list.forEach(item => {
          this.listExamOption.push({value: item.id, label: item.name});
        });
        resolve();
      });
    });
  }

  initForm(): void {
    this.validateForm = this.fb.group({
      radioScore: [0, [Validators.required]],
      difficultyGrade: [null, [Validators.required]],
      countScore: [0, [Validators.required]],
      multiScore: [0, [Validators.required]],
      judgeScore: [0, []],
      timeLimitFlag: [false, [Validators.required]],
      omitScore: [0, [Validators.required]],
      createTime: [null, []],
      duration: [null, [Validators.required]],
      name: [null, [Validators.required]],
      remark: [null, [Validators.required]],
      passScore: [0, [Validators.required]],
      questionTestBankVos: this.fb.array([])
    });
  }

  async ngOnInit(): Promise<any> {
    this.initForm();
    this.difficultyOptions = [...MapPipe.transformMapToArray(MapSet.difficultyLevel)];
    await this.selectList();
    if (this.id) {
      this.getDetail();
    } else {
      this.add();
    }
  }

}
